#!/usr/bin/env python
# encoding: utf-8
"""
    @author:水痕
    @time:2018-08-01 09:12:12:54
    @email:332904234@qq.com
    @version:1.0
    @fileName:register.py
    @describe: 用户注册
"""
from django.shortcuts import render, redirect
from django.shortcuts import HttpResponse
from django.views.generic import View

from django.contrib.auth.hashers import make_password

from users.forms import RegisterForm
from utils.email_send import send_email
from users import models
from io import BytesIO
# 引入生成验证码的类
from utils.captcha import Captcha


class RegisterView(View):
    def get(self, request, *args, **kwargs):
        register_form = RegisterForm()
        # 把数据返回给前端
        return render(request, 'register.html', {'register_form': register_form})

    def post(self, request, *args, **kwargs):
        register_form = RegisterForm(request.POST)
        if register_form.is_valid():
            username = register_form.cleaned_data.get('username', None)
            user_obj = models.UserProfileModel.objects.filter(username=username)
            if user_obj:
                return self.get(request, {'message': '用户名已经存在'})
            password = register_form.cleaned_data.get('password', None)
            new_password = make_password(password=password)
            # 密码加密存入数据库中
            models.UserProfileModel.objects.create(username=username, password=new_password)
            # 用户注册成功后返回登录页面
            return redirect('users:login')
        else:
            print(register_form.errors)
            return self.get(request, {'message': register_form.errors})


# class ActivateEmailView(View):
#     """
#     用户激活邮箱的视图类
#     """
#
#     def get(self, request, *args, **kwargs):
#         # 获取用户的激活码
#         code = kwargs.get('code', None)
#         result = models.EmailVerifyRecordModel.objects.filter(code=code).first()
#         if result:
#             models.UserProfileModel.objects.filter(email=result.email).update(is_active=True)
#             return redirect('users:login')
#         return HttpResponse('邮箱激活码过期')

class CaptchaView(View):
    """
    定义一个图片验证码的视图
    """

    def get(self, request, *args, **kwargs):
        text, image = Captcha.gene_code()
        out = BytesIO()
        image.save(out, 'png')
        out.seek(0)
        # 设置返回请求头
        response = HttpResponse(content_type='image/png')
        response.write(out.read())
        return response
